import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:stock_check/common/config/Config.dart';
import 'package:stock_check/common/dao/DataResult.dart';
import 'package:stock_check/common/dao/UserDao.dart';
import 'package:stock_check/common/storage/LocalStorage.dart';
import 'package:stock_check/common/utils/NavigatorUtils.dart';
import 'package:stock_check/widget/CommonsWidget.dart';
import 'package:stock_check/widget/FlexButton.dart';

class LoginPage extends StatefulWidget {
  static final String routeName = 'login_page';

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String username, password;
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();
  bool _isObscure = true;
  GlobalKey _formKey = new GlobalKey<FormState>();
  String account = '', pwd = '';

  @override
  void dispose() {
    _nameController.dispose();
    _pwdController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      _isObscure = true;
    });
    initParams();
  }

  initParams() async {
    username = await LocalStorage.get(Config.USER_NAME);
    if (username != null) {
      _nameController.value = new TextEditingValue(text: username);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        bottom: false,
        child: Container(
          decoration: BoxDecoration(
            image:DecorationImage(
              image: AssetImage("images/bg.jpg"),
              fit: BoxFit.fill
            )
          ),
          child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                // 点击空白区域收起键盘
                FocusScope.of(context).requestFocus(new FocusNode());
              },
              child: Stack(
                fit: StackFit.loose,
                children: <Widget>[
                  new Center(
                    child: new ClipRect(
                      child: new BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 1.0, sigmaY: 1.0),
                        child: Opacity(
                          opacity: 0.9,
                          child: new Container(
                            width: double.infinity,
                            height: double.infinity,
                            decoration: new BoxDecoration(
                              color: Colors.grey.shade200,
                            ),
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 0.0, horizontal: 20.0),
                              child: buildForm(),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              )),
        ),
      ),
    );
  }

  Form buildForm() {
    return Form(
        key: _formKey,
        onChanged: () {
          username = _nameController.text;
          password = _pwdController.text;
        },
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 120.0),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Icon(Icons.computer, size: 35.0, color: Colors.blue),
                  Text(' 系统登录', style: TextStyle(fontSize: 26.0, color: Colors.blue))
                ],
              ),
              Padding(padding: EdgeInsets.only(bottom: 60.0)),
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(
                  hintText: "请输入账号",
                  prefixIcon: Icon(
                    Icons.person,
                    size: 30.0,
                  ),
                ),
                validator: (v) {
                  return v.trim().length > 0 ? null : '用户名不能空';
                },
              ),
              Padding(padding: EdgeInsets.only(bottom: 10.0)),
              TextFormField(
                obscureText: _isObscure,
                controller: _pwdController,
                decoration: InputDecoration(
                    hintText: "请输入密码",
                    prefixIcon: Icon(Icons.lock, size: 30.0),
                    suffixIcon: IconButton(
                        icon: Icon(_isObscure
                            ? Icons.remove_red_eye
                            : Icons.visibility_off),
                        onPressed: () {
                          setState(() {
                            _isObscure = !_isObscure;
                          });
                        })),
                validator: (v) {
                  return v.trim().length > 0 ? null : '密码不能空';
                },
              ),
              Padding(
                padding: EdgeInsets.only(bottom: 60.0),
              ),
              FlexButton(
                text: '登  录',
                color: Theme.of(context).primaryColor,
                textColor: Colors.white,
                onPress: () {
                  if ((_formKey.currentState as FormState).validate()) {
                    CommonsWidget.showLoadingDialog(context, '登陆中...');
                    UserDao.login(_nameController.text, _pwdController.text)
                        .then((DataResult res) {
                      Navigator.of(context, rootNavigator: true).pop(context);
                      if (res.result == true) {
                        NavigatorUtils.goHome(context);
                      } else {
                        Fluttertoast.showToast(
                            msg: res.data, toastLength: Toast.LENGTH_LONG);
                      }
                    });
                  }
                },
              )
            ],
          ),
        ));
  }
}
